package com.buss.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;

import org.apache.activemq.console.command.CreateCommand;
import org.jweb.core.bean.PageMode;
import org.jweb.core.bean.ReplyDataMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.buss.activity.trans.form.ActiveForm;
import com.buss.activity.trans.vo.ActivedetailVO;
import com.buss.activity.trans.vo.ActivityVO;
import com.buss.admin.service.impl.ActiveServiceimpl;
import com.buss.admin.trans.form.ActivityForm;
import com.buss.common.entity.HxActive;
import com.buss.common.entity.HxActiveDetail;
import com.buss.common.entity.HxUserActive;
import com.buss.common.model.json.EasyUIDataGridResult;
import com.buss.common.model.json.HXResult;
import com.buss.common.service.SysServiceI;

@Controller
@RequestMapping("admin/activemanager")
public class ActiveController {
	
	@Autowired
	private ActiveServiceimpl activityServer;
	
	@Autowired
	private SysServiceI sysService;

	@RequestMapping("/active/list")
	@ResponseBody
	public EasyUIDataGridResult getMemberList(ActivityForm searchForm, HttpServletRequest request) {
		// 分页查询
		searchForm.setStatus("1");
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		int pageNo = Integer.parseInt(request.getParameter("page").toString());
		int pageSize = Integer.parseInt(request.getParameter("rows").toString());
		Map< String, Object> orderby = new HashMap<>();
		orderby.put("createTime", "desc");
		cq.setOrder(orderby);
		// 定义返回数据格式
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		PageMode<HxActive> pageMode = activityServer.list4page(cq, pageNo, pageSize);
		
		List<HxActive> uas = pageMode.getResult();
		List<ActivedetailVO> articleVOs = new ArrayList<>();
		ActivedetailVO articleVO = null;
		for(HxActive ua : uas) {
			articleVO = new ActivedetailVO();
			articleVO.copyEntity(ua);
			articleVOs.add(articleVO);
		}
		// 封装数据
		result.setRows(articleVOs);
		result.setTotal(pageMode.getTotal());
		return result;
	}
	
	@RequestMapping(value="/active/add", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public HXResult getAdd(HxActive active, String content ) {
//		active.setId(163l);
//		active.setPublishTime(new Date(aa));
		try {
			if(active.getPid()!=null) {
				HxActive hxa = activityServer.get(HxActive.class, active.getPid());
				active.setActive(hxa);
			}
			Date datatime  = new Date();
			active.setCreateTime(datatime);
			active.setUpdateTime(datatime);
			active.setStatus(1);
			HxActiveDetail detail = new HxActiveDetail();
			detail.setContent(content);
			detail.setCreateTime(datatime);
			detail.setUpdateTime(datatime);
			detail.setLevelclass(active.getLevelclass());
			active.setActiveDetail(detail);
			activityServer.saveOrUpdate(active);
//			active.setPid(active.getPid());
//			activityServer.updateEntitie(active);
			return HXResult.ok("添加成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return HXResult.build(500, "添加失败");
		}
	}
	
	@RequestMapping(value="/active/edit", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public HXResult editActive(HxActive active, String content ) {
		try {
			
			Date datatime = new Date();
			active.setUpdateTime(datatime);
			active.setStatus(1);
			HxActiveDetail detail = this.activityServer.get(HxActiveDetail.class, active.getId());
			detail.setHxActive(null);
			detail.setContent(content);
			detail.setUpdateTime(datatime);


			String sql = "UPDATE hx_active set pid =? ,title = ? , keywords = ?, summary = ?, source = ?, editor = ?, video_url = ?,img_url = ?,  update_time = ?, publish_time=?, levelclass=? WHERE id = ?";
			this.sysService.executeSql(sql, active.getPid(),active.getTitle(),active.getKeywords(),active.getSummary(),active.getSource(),active.getEditor(),active.getVideoUrl(),active.getImgUrl(),active.getUpdateTime(),active.getPublishTime() , active.getLevelclass(), active.getId());
			String sql2 = null;
			
			if(content == null || "".equals(content)){
				sql2 = "UPDATE hx_active_detail set create_time = ? WHERE id = ?";
				System.out.println(content);
				this.sysService.executeSql(sql2,detail.getUpdateTime(),detail.getId());
				
			}else{
				sql2 = "UPDATE hx_active_detail set content = ? ,create_time = ? WHERE id = ?";
				System.out.println(content);
				this.sysService.executeSql(sql2, content,detail.getUpdateTime(),detail.getId());
			}
			
			
			return HXResult.ok("修改成功");
		} catch (Exception e) {
			
			e.printStackTrace();
			return HXResult.build(500, "修改失败");
		}
	}
	
	@RequestMapping("/active/delete")
	@ResponseBody
	public HXResult delete(String ids, HttpServletRequest request) {
		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				HxActive active = activityServer.get(HxActive.class, Long.parseLong(id));
				active.setStatus(0);
				active.setUpdateTime(new Date());
//				activityServer.updateEntitie(active);
				activityServer.saveOrUpdate(active);
//				activityServer.deleteEntityById(HxActive.class, id);
			}

			return HXResult.ok("删除活动成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器发生错误，删除活动数据失败！");
		}
	}
	
	/**
	 * 活动报名情况统计表
	 * 
	 */
	@RequestMapping("/activityscheck")
	@ResponseBody
	public EasyUIDataGridResult activitys(ActiveForm activityForm, HttpServletRequest request) {
//		ReplyDataMode dataMode = new ReplyDataMode();
		activityForm.setKeywords("99");
		activityForm.setStatus("1");
		CriteriaQuery cq = activityForm.getCriteriaQuery();
		
		int pageNo = Integer.parseInt(request.getParameter("page").toString());
		int pageSize = Integer.parseInt(request.getParameter("rows").toString());

		// 1.查询活动名称
		PageMode  mode = activityServer.list4page(cq,pageNo , pageSize);
		List<HxActive> actives = mode.getResult();
		List<Map<?, ?>> rowss = new ArrayList<>();
		for(HxActive a : actives) {
			Map<String, Object> rows = new HashMap<>();
			rows.put("id", a.getId());
			rows.put("activeName", a.getTitle());
			com.buss.activity.trans.form.ActivityForm form = new com.buss.activity.trans.form.ActivityForm();
			form.setStatus("1");
			form.setAid(a.getId()+"");
			CriteriaQuery cqz = form.getCriteriaQuery();
			// 5.报名总人数
			List<HxUserActive> userActivesz = this.sysService.list(cqz);
			rows.put("totle", userActivesz.size());
			// 2. 普通活动报名情况
			form.setAlessclass("1");
			CriteriaQuery cqp = form.getCriteriaQuery();
			List<HxUserActive> userActive1 = this.sysService.list(cqp);
			rows.put("Ptotle", userActive1.size());
			// 3. VIP报名情况
			form.setAlessclass("2");
			CriteriaQuery cqv = form.getCriteriaQuery();
			List<HxUserActive> userActives2 = this.sysService.list(cqv);
			rows.put("Vtotle", userActives2.size());
			// 4. 权益理事报名情况
			form.setAlessclass("3");
			CriteriaQuery cqq = form.getCriteriaQuery();
			List<HxUserActive> userActives3 = this.sysService.list(cqq);
			rows.put("Qtotle", userActives3.size());
			rowss.add(rows);
		}
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		// 封装数据
		result.setRows(rowss);
		result.setTotal(actives.size());
		return result;
		
	}
	/**
	 * 活动具体活动报名情况统计表
	 * 
	 */
	@RequestMapping("/activityscheckDetail")
	@ResponseBody
	public EasyUIDataGridResult activity(ActiveForm activityForm, HttpServletRequest request) {
//		ReplyDataMode dataMode = new ReplyDataMode();
		activityForm.setKeywords("99");
		activityForm.setStatus("1");
		CriteriaQuery cq = activityForm.getCriteriaQuery();
		
//		int pageNo = Integer.parseInt(request.getParameter("page").toString());
//		int pageSize = Integer.parseInt(request.getParameter("rows").toString());
		int type = Integer.parseInt(request.getParameter("type"));
		// 1.查询活动名称
		List<HxActive> actives = activityServer.list(cq);
		List<Map<?, ?>> rowss = new ArrayList<>();
		for(HxActive a : actives) {
			
			com.buss.activity.trans.form.ActivityForm form = new com.buss.activity.trans.form.ActivityForm();
			form.setStatus("1");
			form.setAid(a.getId()+"");
			CriteriaQuery cqz = form.getCriteriaQuery();
			// 5.报名总人数
			List<HxUserActive> userActivesz = this.sysService.list(cqz);
//			rows.put("totle", userActivesz.size());
			// 2. 普通活动报名情况
			form.setAlessclass("1");
			CriteriaQuery cqp = form.getCriteriaQuery();
			List<HxUserActive> userActive1 = this.sysService.list(cqp);
//			rows.put("Ptotle", userActive1.size());
			// 3. VIP报名情况
			form.setAlessclass("2");
			CriteriaQuery cqv = form.getCriteriaQuery();
			List<HxUserActive> userActives2 = this.sysService.list(cqv);
//			rows.put("Vtotle", userActives2.size());
			// 4. 权益理事报名情况
			form.setAlessclass("3");
			CriteriaQuery cqq = form.getCriteriaQuery();
			List<HxUserActive> userActives3 = this.sysService.list(cqq);
//			rows.put("Qtotle", userActives3.size());
//			rowss.add(rows);
//			EasyUIDataGridResult result = new EasyUIDataGridResult();
			
			if(type==1){
				for(HxUserActive userActive : userActive1){
					Map<String, Object> rows = new HashMap<>();
					rows.put("id", a.getId());
					rows.put("activeName", a.getTitle());
					rows.put("realname", userActive.getHxUser().getRealname());
					rows.put("mphone", userActive.getHxUser().getMphone());
					rows.put("email", userActive.getHxUser().getEmail());
					rows.put("companyname", userActive.getHxUser().getCompanyname());
					rows.put("job", userActive.getHxUser().getJob());
					rowss.add(rows);
				}
				
			} else if(type==2){
				for(HxUserActive userActive : userActives2){
					Map<String, Object> rows = new HashMap<>();
					rows.put("id", a.getId());
					rows.put("activeName", a.getTitle());
					rows.put("realname", userActive.getHxUser().getRealname());
					rows.put("mphone", userActive.getHxUser().getMphone());
					rows.put("email", userActive.getHxUser().getEmail());
					rows.put("companyname", userActive.getHxUser().getCompanyname());
					rows.put("job", userActive.getHxUser().getJob());
					rowss.add(rows);
				}
			} else if(type==3){
				Map<String, Object> rows = new HashMap<>();
				rows.put("id", a.getId());
				rows.put("activeName", a.getTitle());
				for(HxUserActive userActive : userActives3){
					rows.put("realname", userActive.getHxUser().getRealname());
					rows.put("mphone", userActive.getHxUser().getMphone());
					rows.put("email", userActive.getHxUser().getEmail());
					rows.put("companyname", userActive.getHxUser().getCompanyname());
					rows.put("job", userActive.getHxUser().getJob());
					rowss.add(rows);
				}
			} else {
				for(HxUserActive userActive : userActivesz){
					Map<String, Object> rows = new HashMap<>();
					rows.put("id", a.getId());
					rows.put("activeName", a.getTitle());
					rows.put("realname", userActive.getHxUser().getRealname());
					rows.put("mphone", userActive.getHxUser().getMphone());
					rows.put("email", userActive.getHxUser().getEmail());
					rows.put("companyname", userActive.getHxUser().getCompanyname());
					rows.put("job", userActive.getHxUser().getJob());
					rowss.add(rows);
				}
			}
			// 封装数据
//			return result;
		}
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		
		// 封装数据
		result.setRows(rowss);
		result.setTotal(actives.size());
		return result;
		
	}
	/**
	 * 查询user-active的接口
	 */
	private List geetActives(CriteriaQuery cq, int pageNo, int pageSize) {
//		Map< String, Object> orderby = new HashMap<>();
//		orderby.put("createTime", "desc");
//		cq.setOrder(orderby);
		PageMode userArticles = sysService.list4page(cq, pageNo, pageSize);
		List<HxActive> uas = userArticles.getResult();
		List<ActivityVO> articleVOs = new ArrayList<>();
		ActivityVO articleVO = null;
		for(HxActive ua : uas) {
			System.out.println(ua.getActives().size());
			articleVO = new ActivityVO();
			articleVO.copyEntity(ua);
		
			articleVOs.add(articleVO);
		}
		
		return articleVOs;
	}
	/*
	 * 管理员相关页面跳转
	 */
	@RequestMapping("/{path}")
	public String goPath(@PathVariable String path, HttpServletRequest request) {
		String pid = request.getParameter("pid");
		if(pid!=null && !pid.equals("")) {
			request.setAttribute("pid", pid);
		}
		String id = request.getParameter("id");
		if(id!=null && !id.equals("")) {
			request.setAttribute("id", id);
		}
		String type = request.getParameter("type");
		if(type!=null && !type.equals("")) {
			request.setAttribute("type", type);
		}
		return "admin/active/" + path;
	}
}
